<template>
	<div id="single-image-upload">
		<el-upload
			ref="uploadRef"
			action=""
			accept=".jpg,.png"
			list-type="picture-card"
			v-model:file-list="fileList"
			:on-preview="handlePreview"
			:on-remove="handleRemove"
			:http-request="handleHttpRequest"
			:limit="1"
		>
			<el-icon><Plus /></el-icon>
		</el-upload>
		<el-dialog v-model="dialogPreviewVisible" :modal="true">
		    <img w-full :src="previewImage" alt="Preview Image" />
		</el-dialog>		
	</div>
</template>

<script setup>
import * as FileAPI from '@/api/file.js';
import { ref, computed, onMounted, watch , getCurrentInstance} from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
const imageUrl = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})


const dialogPreviewVisible = ref(false);
const fileList = ref([]); //用于图片回显


const { proxy } = getCurrentInstance()
let uploadBtn = undefined;
const uploadRef = ref(null);
onMounted(() => {
	//获取文件上传按钮的DOM元素，每个上传组件有且仅有1个
	uploadBtn = uploadRef.value.$el.getElementsByClassName("el-upload")[0];
	handleImageUrlChanged();	
});

watch(imageUrl, () => {
	handleImageUrlChanged();
});

const handleImageUrlChanged = () => {
	fileList.value = []; 
	if (imageUrl.value) {
		let url = proxy.$fullUrl(imageUrl.value);
		
		fileList.value.push({ url });
		uploadBtn.style.display = "none";
	} else {
		uploadBtn.style.display = "";
	}
};

const handleHttpRequest = async (params) => {	
	// 判断文件是否符合上传要求
	if (!beforeUpload(params.file)) {
		return;
	}

	let formData = new FormData();
	formData.append('file', params.file);
	formData.append('dir', 'admin'); //指定云端upload下的存放目录
	//图片上传成功 result是接口返回数据{code message ,data{url,path}}
	const result = await FileAPI.uploadFile(formData);

	if (result.code != 200) {
		ElMessage.error('图片上传错误：' + result.message);
		return;
	}
	let imageUrlNewValue = result.data.url;
	let url = proxy.$fullUrl(imageUrlNewValue);
	fileList.value = []
	fileList.value.push({ url });	
	
	uploadBtn.style.display = 'none';//不显示上传按钮	
	imageUrl.value = imageUrlNewValue;
};

//移除图片
const handleRemove = async () => {
	// 删除云端存储的文件
	let pathes = [];
	fileList.value.forEach(item => {
		pathes.push(item.url);
	});
	await FileAPI.deleteFile(pathes);

	let imageUrlNewValue = '';
	fileList.value = [];
	
	uploadBtn.style.display = '';	//显示上传按钮
	imageUrl.value = imageUrlNewValue;
};

//文件上传之前调用做一些拦截限制
const beforeUpload = (file) => {
	const isJPGPNG = file.type === 'image/jpg' || file.type === 'image/png';
	const isLt2M = file.size / 1024 / 1024 < 2;

	if (!isJPGPNG) {
		ElMessage.error('上传图片只能是 JPG/PNG 格式!');
	}
	if (!isLt2M) {
		ElMessage.error('上传图片大小不能超过 2MB!');
	}
	return isJPGPNG && isLt2M;
};

//预览图片时调用
const handlePreview = () => {
	dialogPreviewVisible.value = true;
};

const previewImage = computed(()=>{
	// 图片可以预览时，fileList长度肯定大于0
	return fileList.value[0].url;	
});
</script>

<style lang="less" scoped></style>
